package org.phoenixframework.api.course.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.swagger.annotations.ApiModelProperty;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2020/12/22 21:44
 * Description:
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    private final String lastModifiedBy = "lastModifiedBy";
    private final String lastModifiedDate = "lastModifiedDate";

    @Override
    public void insertFill(MetaObject metaObject) {
        String createdBy = "createdBy";
        try {
            Object originalObject = metaObject.getOriginalObject();
            Class<?> aClass = originalObject.getClass();
            Field field = aClass.getDeclaredField("username");
            boolean annotationPresent = field.isAnnotationPresent(ApiModelProperty.class);
            if (annotationPresent) {
                ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                String value = annotation.value();
                System.out.println(value);
                field.setAccessible(true);
                field.set(originalObject, value + UUID.randomUUID().toString());
                System.out.println(originalObject.toString());
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // 异常跳过
            System.out.println("--------");
        }

        if (metaObject.hasSetter(createdBy)) {
            this.strictInsertFill(metaObject, createdBy, () -> 1L, Long.class);
        }
        String createdDate = "createdDate";
        if (metaObject.hasSetter(createdDate)) {
            this.strictInsertFill(metaObject, createdDate, LocalDateTime::now, LocalDateTime.class);
        }
        if (metaObject.hasSetter(lastModifiedBy)) {
            this.strictInsertFill(metaObject, lastModifiedBy, () -> 1L, Long.class);
        }
        if (metaObject.hasSetter(lastModifiedDate)) {
            this.strictInsertFill(metaObject, lastModifiedDate, LocalDateTime::now, LocalDateTime.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(lastModifiedBy)) {
            this.strictInsertFill(metaObject, lastModifiedBy, () -> 1L, Long.class);
        }
        if (metaObject.hasSetter(lastModifiedDate)) {
            this.strictInsertFill(metaObject, lastModifiedDate, LocalDateTime::now, LocalDateTime.class);
        }
    }
}
